package dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import models.User;

import org.bson.types.ObjectId;
import org.jongo.MongoCollection;

import uk.co.panaxiom.playjongo.PlayJongo;
import dao.UserDao;

public class UserDaoImpl implements UserDao {

	private static final MongoCollection users;

	static {
		users = PlayJongo.getCollection("users");
	}

	@Override
	public boolean checkExistByUsername(String username) {
		return users.count("{username: #}", username) > 0;
	}

	@Override
	public void insert(User user) {
		users.save(user);
	}

	@Override
	public User selectByUsernameAndPassword(String username, String password) {
		return users.findOne("{username: #, password: #}", username, password).as(User.class);
	}

	@Override
	public int count(User user) {
		return 0;
	}
	
	@Override
	public List<User> selectAll() {
		List<User> result = new ArrayList<User>();
		Iterator<User> iter = users.find().as(User.class).iterator();
		while (iter.hasNext()) {
			result.add(iter.next());
		}
		return result;
	}
	
	@Override
	public User selectById(String userId){
		return users.findOne(new ObjectId(userId)).as(User.class);
	}
	
	@Override
	public void update(User user){
		users.save(user);
	}

}
